
import { useState,memo,useRef,useEffect, useCallback } from 'react';
import { useLocation } from 'react-router-dom'
import Canvas from '../canvas/Canvas';
import musicstylePC from '../css/pc/music.module.css'
import musicstyleMobile from '../css/mobile/music.module.css'
import { connect } from 'react-redux'
import HtmlTooltip from '../component/HtmlTooltip.jsx'

function Music(props){
  let musicstyle = props.isMobile ? musicstyleMobile:musicstylePC

  const [active,setactive] = useState(0)
  const liRef = useRef(null)
  const audio = useRef(null)
  const bgImg = useRef('')
  const location = useLocation()
  const source = location.state.source
  const list = source.list
  
  const changeSrc = (item,index) => {
    if (active !== index){
      setactive(index)
      audio.current.src = item.path
    }
    audio.current.play()
  }

  const play = () => {
    audio.current.play()
  }
  const pause = () => {
    audio.current.pause()
  }

  const playnext = () => {
    let index = active+1
    if (index >= list.length) index = 0
    setactive(index)
    audio.current.src = list[index].path
    audio.current.play()
  }
  const playpre = () => {
    let index = active-1 >=0 ? active-1:0
    setactive(index)
    audio.current.src = list[index].path
    audio.current.play()
  }

  const volChange = (e) => {
    audio.current.volume = e.target.value/100

  }


  useEffect(() => {
    document.title =`${location.state.title}  ` + location.state.source.directory
    if (list && list.length) {
      let index = Math.round(Math.random() * (list.length - 1))
      audio.current.src = list[index].path
      setactive(index)
    }
  },[])
  
  // 避免监听事件 产生闭包
  useEffect(() => {
    liRef.current.scrollIntoView({block:'center',behavior:'smooth'})
    audio.current.onended = playnext
    return () => {
      if(audio.current){
        audio.current.onended = null
      }
    }
  },[active])



  return <div className={musicstyle.music}>
    <div className={musicstyle.headtitle}><h1 className={musicstyle.title}>{list[active].name}</h1></div>
    <div className={musicstyle.musicplayer}>
      <audio style={{display:'none'}} ref={audio} className={musicstyle.audio} crossOrigin="anonymous" id='audio' controls autoPlay ></audio>
    </div>
    <Canvas {...{postImg:list[active].imgpath,play,pause,playnext,playpre,volChange,isMobile:props.isMobile}}></Canvas>
    {/* <Clock></Clock> */}
    <div  className={musicstyle.musiclist}>
      <ul>
        {
          list.map((item,index) => <li className={active === index ? musicstyle.active:''} ref={(current) => {if(active === index){ liRef.current = current }} } onClick={() => changeSrc(item,index)} key={index}><HtmlTooltip title={item.name} placement="top"  disableInteractive><span>{item.name}</span></HtmlTooltip></li>)
        }
      </ul>
    </div>
  </div>
}

const mapProps = (state) => {
  return state.counter
}



export default connect(mapProps)(memo(Music))